package com.demo.service.impl;

import com.demo.common.base.ResultModel;
import com.demo.dao.MenuMapper;
import com.demo.model.Menu;
import com.demo.model.UserInfo;
import com.demo.service.MenuService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: MenuServiceImpl
 * @Author: ChenXueLi
 * @Date: 2018-10-05 18:44
 */
@Log
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 获取菜单信息
     * @param resultModel
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel getMenuList(ResultModel resultModel, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取所有的菜单信息
        List<Menu> menuList = menuMapper.getMenuList();
//        Map<Integer, Menu> menuMap = menuList.stream().collect(Collectors.toMap(Menu::getMenuCode, menu -> menu));
        Map<Integer, List<Menu>> integerListMap = new HashMap<>();
        // 获取当前角色拥有的权限信息
        UserInfo loginUser = resultModel.getUserInfo();
        // 筛选菜单
        for(Menu menu : menuList) {
            if(!integerListMap.containsKey(menu.getFkMenuCode())) {
                integerListMap.put(menu.getFkMenuCode(), new ArrayList<Menu>());
            }
            integerListMap.get(menu.getFkMenuCode()).add(menu);
        }
        // 找到菜单父节点为0的
        List<Menu> parentMenuList = integerListMap.get(0);
        for(Menu menu : parentMenuList) {
            // 寻找二级菜单
            if(integerListMap.containsKey(menu.getMenuCode())) {
                List<Menu> secondMenuList = integerListMap.get(menu.getMenuCode());
                // 寻找三级菜单
                for(Menu m : secondMenuList) {
                    if(integerListMap.containsKey(m.getMenuCode())) {
                        m.setSubMenuList(integerListMap.get(m.getMenuCode()));
                    }
                }
                menu.setSubMenuList(secondMenuList);
            }
        }

        resultModel.setData(parentMenuList);
        resultModel.info("查询成功");
        return resultModel;
    }
}
